import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router/index'
Vue.use(Vuex)
/**
 *@method
 *@description vuex持久化插件
 * @param {Vuex} store veux对象 
 */

const storePersist = (store) => {
  
  const key = 'VUEX_STORE_KEY';
  const storage = window.sessionStorage;

  const data = storage.getItem(key);
  data && store.replaceState(JSON.parse(data));
  store.subscribe(function(mutation,state){
    console.log(mutation);
    storage.setItem(key, JSON.stringify(state));
  });
}

export default new Vuex.Store({
  state: {
    /**
     * 登录用户
     */
    user:{},
    /**
     * 菜单列表
     */
    menus:[],
  },
  getters: {
  },
  mutations: {
  /**
   * 设置用户信息
   */
  setUser(state,payload){
    state.user = payload;
  },
  /**
   * 设置菜单列表
   */
  setMenus(state,payload){
    state.menus = payload
  }
  },
  getters:{
    /**
     * token
     */
    token(state){
      return state.user.token;
    }
  },
  actions: {
    /**
     * 退出 
    */
    exit({commit}){
      commit('setUser',{});
      router.push({name:'Login'});
    }
  },
  modules: {
  },
  plugins:[storePersist]
})
